let canvas = document.getElementById('canvas');
let audio = document.getElementById('audio');
var range = document.querySelector('#range');
var canvasCtx = document.getElementById('canvas').getContext('2d');

async function _play() {
    var audioCtx = new(window.AudioContext || window.webkitAudioContext)();
    // Create a MediaElementAudioSourceNode
    // Feed the HTMLMediaElement into it
    // var source = audioCtx.createMediaElementSource(audio);
    var stream = await navigator.mediaDevices.getUserMedia({ audio: true });
    let source = audioCtx.createMediaStreamSource(stream); //创建一个新的 关联 对象
    // video.src = URL.createObjectURL(mediaSource);
    audio.srcObject = stream
    // Create a gain node
    var gainNode = audioCtx.createGain();
    gainNode.gain.value = 0;
    // Create variables to store mouse pointer Y coordinate
    // and HEIGHT of screen
    range.oninput = function() {
        gainNode.gain.value = range.value / 10000;
        console.log(range.value)
    }
    // connect the AudioBufferSourceNode to the gainNode
    // and the gainNode to the destination, so we can play the
    // music and adjust the volume using the mouse cursor

    var analyser = audioCtx.createAnalyser();
    analyser.minDecibels = -90;//结果范围的最小值
    analyser.maxDecibels = -10;//结果范围的最大值
    analyser.smoothingTimeConstant  = 0.9;//分析帧的平均常数 0-1  默认值为 0.8
    // 一个双精度值，代表用于缩放FFT分析数据的最小分贝值，其中0dB是可能的最大声音，-10dB是该值的十分之一，依此类推。默认值为-100dB。

    source.connect(analyser);
    let WIDTH = 1000
    let HEIGHT = 300
    analyser.fftSize = 2048;
    var bufferLength = analyser.frequencyBinCount;
    var dataArray = new Uint8Array(bufferLength);

    function draw() {
        drawVisual = requestAnimationFrame(draw);

        analyser.getByteFrequencyData(dataArray);

        canvasCtx.fillStyle = 'rgb(0, 0, 0)';
        canvasCtx.fillRect(0, 0, WIDTH, HEIGHT);

        var barWidth = (WIDTH / bufferLength) * 2.5;
        var barHeight;
        var x = 0;

        for (var i = 0; i < bufferLength; i++) {
            barHeight = dataArray[i];

            canvasCtx.fillStyle = 'rgb(' + (barHeight + 100) + ',50,50)';
            canvasCtx.fillRect(x, HEIGHT - barHeight / 2, barWidth, barHeight / 2);

            x += barWidth + 1;
        }
    };
    draw()
    source.connect(gainNode);
    gainNode.connect(audioCtx.destination);
    // audio.play()
    source.start()
}
